using Autofac.Extensions.DependencyInjection;
using Autofac;
using HSGD.Api.Filter;
using HSGD.Common.Core;
using HSGD.Common;
using HSGD.Extensions.ServiceExtensions;
using HSGD.Extensions;
using System.IdentityModel.Tokens.Jwt;
using Microsoft.AspNetCore.Mvc;

public static class ApplicationSetup {
    public static WebApplicationBuilder ConfigureServices(WebApplicationBuilder builder) {
        ConfigureAutofac(builder);

        ConfigureBaseServices(builder.Services, builder.Configuration);

        ConfigureAuth(builder.Services);

        ConfigureApi(builder.Services);

        return builder;
    }

    private static void ConfigureAutofac(WebApplicationBuilder builder) {
        builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory())
            .ConfigureContainer<ContainerBuilder>(builder => {
                builder.RegisterModule<AutofacModuleRegister>();
                builder.RegisterModule<AutofacPropertityModuleReg>();
            })
            .ConfigureAppConfiguration((hostingContext, config) => {
                hostingContext.Configuration.ConfigureApplication();
            });
        builder.ConfigureApplication();

        //JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
    }

    private static void ConfigureBaseServices(IServiceCollection services, IConfiguration configuration) {
        services.AddSingleton(new AppSettings(configuration));
        services.AddAllOptionRegister();
        services.AddCacheSetup();
        services.AddSqlSugarSetup();
        services.AddAutoMapperSetup();
        services.AddCorsSetup();
        services.AddHttpContextSetup();
        services.AddMinIOSetup();
    }

    private static void ConfigureAuth(IServiceCollection services) {
        JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
        services.AddAuthenticationJWTSetup();
    }

    private static void ConfigureApi(IServiceCollection services) {
        services.AddEndpointsApiExplorer();
        services.AddSwaggerGen();

        services.AddControllers(o => {
            o.Filters.Add(typeof(GlobalExceptionsFilter));
            o.Conventions.Insert(0, new GlobalRoutePrefixFilter(new RouteAttribute(RoutePrefix.Name)));
        }).AddConfigureApiBehaviorOptionsSetup();
    }
}